package com.wmz.aspect;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author wmz
 * @date 2024/7/19 0:33
 * @description SysLogAspect
 */
@Component
@Slf4j
@Aspect
public class SysLogAspect {
    /**
     * 切入点表达式
     */
    public static final String POINT_CUT = "execution ( * com.wmz.controller.*.*(..))";
    @Around(value = POINT_CUT)
    public Object loadAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        //获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 获取ip地址
        String remoteHost = request.getRemoteHost();
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        //获取请求方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodString = method.toString();
        //获取ApiOperation注解
        ApiOperation apiOperation = method.getDeclaredAnnotation(ApiOperation.class);
        //判断注解是否为空
        String operation = "";
        if(ObjectUtils.isNotNull(apiOperation)) {
            // 获取描述
            operation = apiOperation.value();
        }
        //判断参数是否为文件类型
        String finalArgs = "";
        if(ObjectUtils.isNotNull(args) && args.length > 0 && args[0] instanceof MultipartFile) {
            finalArgs = "file";
        } else {
            finalArgs = JSONObject.toJSONString(apiOperation);
        }
        // 开始时间
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = joinPoint.proceed(args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        // 结束时间
        long endTime = System.currentTimeMillis();
        // 执行时长
        Long execTime = endTime - startTime;
        log.info("调用时间：{}，请求接口路径：{}，请求IP地址：{}，方法名称：{}，执行时长：{}，方法描述：{}",
                new Date(),requestURI,remoteHost,methodString,execTime,operation);
        return result;
    }
}
